package com.fare.taluo.web.action;

import java.io.File;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import com.common.remote.ftp.FtpConfig;
import com.common.remote.sftp.SFtpFileTransferClient;
import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.application.ExcelInfoApplication;
import com.fare.taluo.conf.system.DefaultPropertiesLoader;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.vo.core.ExcelInfoVO;
import com.fare.util.ReportProperties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class ExcelAutoDelete {

	public void executeDel() throws Exception {
		ExcelInfoApplication excelInfoApplication = InstanceFactory
				.getInstance(ExcelInfoApplication.class);
		String daysType = DefaultPropertiesLoader.getExcelDay();
		int days = 1 - Integer.parseInt(daysType);
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, days);
		calendar.add(Calendar.HOUR_OF_DAY, -1);
		String oldDays = DateUtils.formatDay(calendar.getTime(), "yyyyMMddHH");
		List<ExcelInfoVO> listFile = excelInfoApplication.findByTime(oldDays);
		ReportProperties rp;

		rp = ReportProperties.getInstance();
		// ftp连接配置
		FtpConfig config = new FtpConfig(rp.getAddress(), rp.getPort(),
				rp.getUserName(), rp.getPassword());
		SFtpFileTransferClient sftpClient = new SFtpFileTransferClient(config);
		Channel channel = null;
		boolean flag = false;
		try {
			sftpClient.connect();

			if (listFile != null) {
				for (ExcelInfoVO vo : listFile) {
					if (sftpClient.isFileExists(rp.getPath() + vo.getPath())) {
						flag = sftpClient.delete(rp.getPath() + vo.getPath());
						if (flag) {
							excelInfoApplication.delete(vo);
						}
					}
					Date date1 = DateUtils.strToDate(vo.getDateType(),
							"yyyyMMddHH");
					String dateType = DateUtils.dateToStr(date1,
							"yyyy-MM-dd HH");
					String fileName = rp.getPath()
							+ vo.getPath().substring(0, 20) + dateType + ".zip";
					if (sftpClient.isFileExists(fileName)) {
						sftpClient.delete(fileName);
					}
					String[] dirs = (rp.getPath() + vo.getPath()).split("/");
					String dir = findDir(dirs);
					for (;;) {
						if(dir.equalsIgnoreCase(rp.getPath()) || dir.equals(rp.getPath()+"/")){
							break;
						}
						if (sftpClient.isDirectoryExists(dir)) {
							String[] r = sftpClient.list(dir);
							if (r == null || r.length == 0) {
								JSch jsch = new JSch();
								Session session = jsch.getSession(
										config.getUserName(),
										config.getFtpUrlorIp(),
										config.getFtpPort());
								session.setPassword(config.getPassword());
								Hashtable<String, String> config1 = new Hashtable<String, String>();
								config1.put("StrictHostKeyChecking", "no");
								session.setConfig(config1);

								session.connect();
								channel = session.openChannel("sftp");
								channel.connect();
								ChannelSftp c = (ChannelSftp) channel;
								c.rmdir(dir);
								channel.disconnect();
								dir = findDir(dir.split("/"));
							} else {
								break;
							}
						}
					}

				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (sftpClient != null) {
				sftpClient.disconnect();
			}
			if (channel != null) {
				channel.disconnect();
			}
		}

	}

	private String findDir(String[] dirs) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < dirs.length - 1; i++) {
			if (i == dirs.length - 2) {
				buffer.append(dirs[i]);
			} else {
				buffer.append(dirs[i] + "/");
			}

		}
		return buffer.toString();
	}

}
